<template>
	<view class="content">
		<uni-list>
			<uni-list-item title="用户头像" clickable>
				<template #footer>
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="hanldeChooseAvatar">
						<image class="avatar" :src="avatarUrl"></image>
					</button>
				</template>
			</uni-list-item>
			<uni-list-item title="用户昵称">
				<template #footer>
					<input type="nickname" :value="userStore.nickname" placeholder="请输入昵称" confirm-type="确认"
						@blur="handleChangeNickname" />
				</template>
			</uni-list-item>
			<uni-list-item title="性别">
				<template #footer>
					<uni-data-checkbox v-model="userStore.gender" :localdata="genderOptions"
						@change="handleChangeGender"></uni-data-checkbox>
				</template>
			</uni-list-item>
			<uni-list-item title="手机号">
				<template #footer>
					<input type="number" inputmode="tel" :value="userStore.phone" confirm-type="确认" placeholder="请输入手机号"
						@blur="handleChangePhone" />
				</template>
			</uni-list-item>
		</uni-list>
	</view>
</template>

<script setup>
	import {
		computed,
		ref
	} from "vue"
	import {
		useUserStore
	} from "@/stores/user.js"
	import {
		SERVER_URL
	} from "@/config/index.js"

	const userStore = useUserStore()

	const avatarUrl = computed(() => {
		if (userStore.avatar) {
			return SERVER_URL + userStore.avatar
		} else {
			return "/static/images/default_avatar.png"
		}
	})

	const genderOptions = ref([{
		text: '男',
		value: 1
	}, {
		text: '女',
		value: 0
	}, {
		text: '未知',
		value: -1
	}])


	const updateInfo = (data) => {
		uni.showLoading()
		uni.request({
			url: SERVER_URL + '/customer/info',
			method: "PUT",
			data,
			header: {
				"content-type": "application/json",
				"authorization": userStore.token
			},
			success: (res) => {
				console.log(res);
				userStore.$patch(res.data)
			},
			complete: () => {
				uni.hideLoading()
			}
		});
	}


	const hanldeChooseAvatar = (e) => {
		console.log(e)

		uni.uploadFile({
			url: SERVER_URL + "/images/upload",
			filePath: e.detail.avatarUrl,
			name: "file",
			success: (res) => {
				if (res.statusCode === 200) {
					const data = JSON.parse(res.data)
					console.log(res)
					console.log(`/static/images/${data.folder}/${data.hash}.${data.format}`)

					updateInfo({
						avatar: `/static/images/${data.folder}/${data.hash}.${data.format}`
					})
				}
			}
		})


	}

	const handleChangeNickname = (e) => {
		updateInfo({
			nickname: e.detail.value
		})
	}

	const handleChangeGender = (e) => {
		updateInfo({
			gender: e.detail.value
		})
	}

	const handleChangePhone = (e) => {
		updateInfo({
			phone: e.detail.value
		})
	}
</script>

<style scoped lang="scss">
	:deep(.uni-list) {
		.uni-list-item__content {
			justify-content: center;
		}
	}

	.avatar-wrapper {
		padding: 0;
		width: 48px;
		height: 48px;

		.avatar {
			width: 100%;
			height: 100%;
		}
	}
</style>